'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: base_service.py
* @Time: 2025/9/23
* @All Rights Reserve By Brtc
'''
from typing import Any, Optional

from internal.exception.exception import FailException
from pkg.sqlachemy.sqlalchemy import SQLAlchemy


class BaseService:
    db:SQLAlchemy
    def create(self, model:Any, **kwargs)->Any:
        """根据传递的模型类 + 键值 创建对应的数据库记录"""
        with self.db.auto_commit():
            model_instance = model(**kwargs)
            self.db.session.add(model_instance)
        return model_instance


    def delete(self, model_instance:Any)-> Any:
        """根据传递的模型实例删除对应的数据记录"""
        with self.db.auto_commit():
            self.db.session.delete(model_instance)
        return model_instance


    def update(self, model_instance:Any, **kwargs)->Any:
        """根据传递的模型实例 + 键值对信息更新数据库记录"""
        with self.db.auto_commit():
            for field, value in kwargs.items():
                if hasattr(model_instance, field):
                    setattr(model_instance, field, value)
                else:
                    raise FailException("数据更新失败！！")
        return  model_instance


    def get(self, model:Any, primary_key:Any)->Optional[Any]:
        """根据传递的模型类 + 主键 获取唯一的数据"""
        return self.db.session.query(model).get(primary_key)